package controller;

import db.ItemDAO;
import db.OrderDAO;
import java.security.InvalidParameterException;

import model.Customer;
import model.Item;
import model.NoSuchItemException;
import model.Order;
import model.Delivery;
import model.OrderLineItem;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

/**
 *
 * @author Mads Nielsen
 */
public class OrderController {

    private Order currentOrder;

    public OrderController() {
        startSale();
    }

    public void startSale() {
        currentOrder = new Order();
    }

    /**
     * Adds item to current sale in specified quantity
     *
     * @param itemNo
     * @param qty
     * @throws NoSuchItemException
     *             if item identifier does not match any known item
     * @throws NoOpenSaleException
     *             if no sale is currently open
     */
    public void addItem(String itemNo, int qty) throws NoSuchItemException,
            NoOpenSaleException {

        if (currentOrder == null) {
            throw new NoOpenSaleException();
        }

        if (0 > qty) {
            throw new InvalidParameterException(
                    "Quantity must be larger than zero");
        }
        
        // find item
        Item item = new ItemDAO().findOne("item_no = ?", itemNo);
        
        if(item == null){
            throw new NoSuchItemException();
        }
        
        currentOrder.addItem(item, qty);
    }

    public void closeSale() {
        currentOrder.close();
        
        new OrderDAO().insert(currentOrder); // insert to database
        
    }

    public void unsetCustomer() {
        currentOrder.setCustomer(null);
    }

    public void createDelivery(String name, String address, int zipCode,
            String city, double price) {
        throw new NotImplementedException();
    }

    public Order getSale() {
        return currentOrder;
    }

    public OrderLineItem getSaleLine(int index) {
        return currentOrder.getLine(index);
    }

    public void removeSaleLine(OrderLineItem line) {
        currentOrder.removeLine(line);
    }

    public OrderLineItem[] getSaleLineItems() {
        return currentOrder.getLineItems();
    }

    public void setDiscount(double discount) {
        currentOrder.setDiscount(discount);
    }

    public double getSaleSavings() {
        return currentOrder.getSavings();
    }

    public void clearSaleDelivery() {
        currentOrder.clearDelivery();
    }
}
